<template>
    <div>
        <Form ref="createdProjectForm" :model="createdProjectForm" :rules="createdProjectRuleValidate" :label-width="120">
            <FormItem label="名称" prop="name">
                <Input v-model.trim="createdProjectForm.name" placeholder="名称" @keydown.native.enter.prevent="searchHandle"></Input>
            </FormItem>
            <!-- <FormItem label="训练ID" prop="trainId">
                <Input v-model.trim="createdProjectForm.trainId" placeholder="训练ID"></Input>
            </FormItem> -->
            <FormItem label="配额" prop="quotaTypeId" v-if="false">
                <Select filterable v-model="createdProjectForm.quotaTypeId">
                    <Option value="2">小型</Option>
                    <Option value="3">中型</Option>
                    <Option value="4">大型</Option>
                    <Option value="5">超大型</Option>
                </Select>
            </FormItem>
            <FormItem label="描述" prop="description">
                <Input v-model.trim="createdProjectForm.description" type="textarea" :maxlength="200" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述"></Input>
            </FormItem>
            <FormItem label="支持分布式" prop="type" v-if="distributedRange && $store.state.common.showDistributed">
                    <RadioGroup v-model="createdProjectForm.type">
                        <Radio label="distributed">是</Radio>
                        <Radio label="normal">否</Radio>
                    </RadioGroup>
                </FormItem>
            <FormItem label="工程模板" prop="envtempid">
                <Button type="primary" ghost @click="toPlateTabs">选择</Button>
                <div class="chose-wrap" v-show="useTemplateId != ''">
                    <div style="display: flex;justify-content: flex-start;align-items: center">
                        <img src="../../assets/exper/template.png" class="chose-s-icon">
                        <div class="chose-name">{{this.useTempName}}</div>
                    </div>
                    <img src="../../assets/globalIcon/dis-del.png" style="width: 13px;height: 14px;cursor: pointer" @click="clearTemp">
                </div>
            </FormItem>
            <FormItem FormItem label="模式" prop="mode" v-show="useTemplateId != ''">
                <RadioGroup v-model="createdProjectForm.mode" type="button" >
                    <Poptip trigger="hover" title="完全导入" content="导入模板所有信息">
                        <Radio label="complete">完全导入</Radio>
                    </Poptip>
                    <Poptip trigger="hover" title="强制导入" content="自动替换已丢失的镜像和配额">
                        <Radio label="force">强制导入</Radio>
                    </Poptip>
                    <Poptip trigger="hover" title="仅拓扑结构" content="仅导入拓扑结构，不导入节点配置">
                        <Radio label="only_structure">仅拓扑结构</Radio>
                    </Poptip>
                </RadioGroup>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="createdProSubmit('createdProjectForm')" :loading="submitProjectLoading">确定</Button>
                <Button @click="createdProReset('createdProjectForm')" style="margin-left: 8px">重置</Button>
            </FormItem>
        </Form>
        <!--工程模板-->
        <DrawerPage 
            v-model="addDeviceModel" 
            select
            title="工程模板"
            :columns="templateCol" 
            :data="templateList" 
            :loading="proTemLoading"
            :total=templateTotal 
            :size.sync="templatePageSize"
            :page.sync="templatePage"
            @queryFun="toPlateTabs"
            style="z-index:2999">
            <template slot="search">
                <i-select clearable  placeholder="可见范围" v-model="selectProTemModel" style="width: 150px;margin-left: 15px;" @on-change="changeTemplate">
                    <i-option value="range">平台</i-option>
                    <i-option value="system">系统</i-option>
                    <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
                </i-select>
                <Input v-model.trim="searchTemNameInput" placeholder="模板名称" clearable @on-change="searchTemNameBtn" style="width: 180px;margin-left: 15px;"/>
                <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshTem()"><i class="el-icon-refresh-right" /></Button>
            </template>
        </DrawerPage>
    </div>
</template>
<script>
    import $ from 'jquery'
    // import cookieUse from '@/libs/cookie.js'
    // import encryption from '@/libs/encryption.js'
    import {creatBlankPro} from '@/api/homer.js'
    import {getTemplateData,getTempInfpByID} from '@/api/proTemplate.js'
    import { validateName ,validateName1} from '@/libs/reg.js'
    export default {
        name:'creatProject',
        props:['proId','proName','message'],
        data () {
            return {
                // distributedRange:false,//是否是主靶场
                USER_ID:'',
                fullHeight: document.documentElement.clientHeight,
                fullWidth:document.documentElement.clientWidth,
                contentHei:'0px',
                // 普通工程创建
                createdProjectForm:{
                    name:'',
                    description:'',
                    //quotaTypeId:'2',
                    trainId:'0',
                    type:'normal',
                    mode:'complete',
                },
                createdProjectRuleValidate:{
                    name:[
                        { required: true, max: 64,message: '工程名称长度为1—64个字符', trigger: 'change' },
                        { validator: validateName1, trigger: 'change' }
                    ],
                    description:[
                        { max: 200, message: '描述文字不能超过200个字符', trigger: 'change' },
                    ]
                },
                submitProjectLoading:false,
                useTemplateId:this.proId,
                useTempName:this.proName,
                // 工程模板
                addDeviceModel:false,
                templatePage:1,
                templatePageSize:14,
                templateTotal:0,
                templateList:[],
                templateCol:[
                    {
                        title:'序号',
                        type:'index',
                        width:60,
                        align:'left',
                        tooltip: true
                    },
                    {
                        title:'模板名称',
                        key:'name',
                        align:'left',
                        tooltip: true
                    },
                    {
                        title:'可见范围',
                        key:'visibility',
                        width:100,
                        align:'left',
                        render:(h,params)=>{
                            let text = ''
                            if(params.row.visibility === 'share'){
                                text = '单位'
                            }else if(params.row.visibility === 'private'){
                                text = '个人'
                            }else{
                                text = '系统'
                            }
                            return h('div',text)
                        }
                    },
                    {
                        title:'创建者',
                        key:'creatorName',
                        width:150,
                        align:'left',
                        tooltip: true
                    },
                    {
                        title:'描述',
                        key:'description',
                        align:'left',
                        tooltip: true
                    },
                    {
                        title:'创建时间',
                        key:'created',
                        width:170,
                        align:'left',
                        tooltip: true
                    },
                    {
                        title:'操作',
                        key:'action',
                        align:'left',
                        width:120,
                        render:(h,params)=>{
                            let text = ''
                            if(params.row.tempUserFlag){
                                text = '已用'
                            }else {
                                text = '使用'
                            }
                            return h('a',{
                                style: {
                                    'display': 'flex',
                                    'justify-content': 'flex-start',
                                    'align-items': 'center',
                                    color:params.row.tempUserFlag?'#0cd758':'#2f70ff'
                                },
                            },[
                                h('div', {
                                    on: {
                                        'click': ()=>{
                                            this.chooseTemp(params)
                                        },
                                    },
                                    style:{
                                        'margin-left':'15px'

                        
                                    }
                                }, [
                                    h('img', {
                                        attrs: {
                                            src: params.row.tempUserFlag?require('../../assets/globalIcon/choosed_green.png'):require('../../assets/globalIcon/del.png'),
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            'margin-right':'5px',
                                            'vertical-align': 'middle',
                                            width:'15px',
                                            height:'15px',
                                            display:'inline-block',
                                            transform:params.row.tempUserFlag?'rotate(0deg)':'rotate(45deg)',
                                            'margin-top':'-4PX'
                                            // filter: 'drop-shadow(0 0 0 var(--url-color))'
                                        },
                                    }),
                                    h('span',{
                                        style: {
                                            cursor: 'pointer',
                                        },
                                    },text)
                                ])
                            ])
                        }
                    },
                ],
                searchTemplateName:'',
                proTemLoading:false,
                searchTemNameInput:'',
                selectProTemModel:'designer',
                templateVisibility:'',
                setUserTableHei:'700',
            }
        },
        created(){
            // 获取用户id
            // let November = sessionStorage.getItem('November')
            // November = JSON.parse(encryption.SelfUseDecrypt(November))
            // this.USER_ID = November.userId
        },
        mounted(){
            // this.setStyle()
            $('.form-wrap .ivu-divider-horizontal').css({
                margin:0
            })
            // window.onresize = () => {
            //     this.setStyle()
            // }
            // this.distributedRange = this.$store.state.user.distributedRange
        },
        computed:{
            distributedRange(){
                return this.$store.state.user.distributedRange
            }
        },
        methods:{
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.contentHei =   this.fullHeight - 80 - 60 - 77 -101 +'px'  // 80是头部高度  60是上下padding
                this.setUserTableHei = this.fullHeight - 212
                this.templatePageSize = Math.floor(this.setUserTableHei/50) - 1
            },
            // 阻止回车键导致的刷新
            searchHandle(){

            },
            // 创建新工程
            createdProSubmit(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        this.submitProjectLoading = true
                        let temId = ''
                        if(this.useTemplateId != ''){
                            temId = `${this.useTemplateId}`
                        }
                        this.createdProjectForm.trainId = parseInt(this.createdProjectForm.trainId)
                        creatBlankPro(temId,this.createdProjectForm,this.createdProjectForm.mode)
                            .then(res=>{
                              console.log('createdProSubmit   金额口啊啊啊-----',res.data.data)
                                let resultData = res.data.attribute?res.data.attribute.result:''
                                if(res.data.code === 1){
                                    // if(resultData.status === 0){
                                        this.message !== false && this.$Message.success('工程创建成功！')
                                        this.$emit('creatProModalStatus',resultData)
                                        this.$emit('setSceneUpdate',false)
                                    //}
                                    // 取消模板
                                    this.useTempName = ''
                                    this.useTemplateId = ''
                                }else if(res.data.code === 2){
                                    this.$Message.info({
                                        content:res.data.message,
                                        duration:3,
                                    })
                                    this.$emit('creatProModalStatus',resultData)
                                    // 取消模板
                                    this.useTempName = ''
                                    this.useTemplateId = ''
                                }else {
                                    this.$Message.error({
                                        content:res.data.message,
                                        duration:3,
                                    })
                                }
                                this.submitProjectLoading = false
                            })
                            .catch(err=>{
                                console.log(err)
                                this.submitProjectLoading = false
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            createdProReset(name){
                this.useTempName = ''
                this.useTemplateId = ''
                this.$refs[name].resetFields();
            },
            // 选择工程模板
            toPlateTabs(){
                this.addDeviceModel = true
                this.templateList = []
                let query = {
                    pageIndex: this.templatePage,
                    pageSize: this.templatePageSize,
                };
                let params = {
                    name:this.searchTemplateName,
                    visibility:this.templateVisibility,
                    type:'project',
                }
                this.proTemLoading = true
                getTemplateData(params,query)
                    .then(res=>{
                        if(res.data.code === 1){
                            let pateInfo = res.data.data
                            this.templateTotal = +pateInfo.total
                            let items = pateInfo.items
                            for(let i=0;i<items.length;i++){
                                items[i].tempUserFlag = false
                                if(items[i].id === this.useTemplateId){
                                    items[i].tempUserFlag = true
                                }
                            }
                            this.templateList = items
                        }else {
                            this.templateList = []
                            this.templateTotal = 0
                        }
                        this.proTemLoading = false
                    })
                    .catch(err=>{
                        this.proTemLoading = false
                        console.log(err)
                    })
            },
            temOnChange(val){
                this.templatePage = val
                this.toPlateTabs()
            },
            changeTemplate(val){
                this.templatePage = 1
                this.templateVisibility = val
                this.toPlateTabs()
            },
            searchTemNameBtn(val){
                this.templatePage = 1
                this.searchTemplateName = this.searchTemNameInput
                this.toPlateTabs()
            },
            refreshTem(){
                this.templatePage = 1
                this.searchTemplateName = ''
                this.searchTemNameInput = ''
                this.templateVisibility = ''
                this.selectProTemModel = 'designer'
                this.toPlateTabs()
            },
            closeDistribution(){
                this.addDeviceModel = false
            },
            chooseTemp(params){
                if(!params.row.tempUserFlag){
                    let _index = params.row._index
                    for(let i=0;i<this.templateList.length;i++){
                        this.templateList[i].tempUserFlag = false
                    }
                    this.$set(this.templateList[_index],'tempUserFlag',true)
                    this.useTempName = params.row.name
                    this.useTemplateId =  params.row.id
                }
            },
            // 清除模板
            clearTemp(){
                this.useTempName = ''
                this.useTemplateId = ''
            },
        }
    }
</script>
<style scoped>
    .chose-wrap{
        display: flex;
        justify-content: space-between;
        padding: 3px 8px;
        background-color: var(--table-tr-hover-color);
        align-items: center;
        margin-top: 10px;
    }
    .chose-name{
        width: 300px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space:nowrap;
    }
    .chose-s-icon{
        width: 15px;
        height: 17px;
        display: inline-block;
        margin-bottom: 1px;
        margin-right: 10px;
    }
    .project-page-drawer{
        position: relative;
    }
</style>
<style>
    .project-page-drawer .ivu-drawer-wrap{
        z-index: 1200;
    }
    .project-page-drawer .ivu-drawer-mask{
        z-index: 1200;
    }
    .project-page-drawer .ivu-drawer-body{
        overflow: inherit;
    }
</style>
